package com.ruoyi.ftrl.io.server;




import com.ruoyi.ftrl.io.server.common.StringUtil;
import com.ruoyi.ftrl.io.server.domain.BTypeCollector;
import com.ruoyi.ftrl.io.server.domain.MyPacket;
import com.ruoyi.ftrl.mapper.TemperatureControlMapper;
import com.ruoyi.ftrl.service.MessagePublisher;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.server.intf.TioServerHandler;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;


public class MyServerAioHandler extends AbstractAioHandler implements TioServerHandler {
    private MqttClient mqttClient; // MQTT 客户端

    private TemperatureControlMapper temperatureControlMapper;

    private MessagePublisher messagePublisher;

    public MyServerAioHandler(TemperatureControlMapper temperatureControlMapper, MessagePublisher messagePublisher) {
        this.temperatureControlMapper = temperatureControlMapper;
        this.messagePublisher = messagePublisher;
    }

    public void setMqttClient(MqttClient mqttClient) {
        this.mqttClient = mqttClient; // 设置 MQTT 客户端
    }
    /**
     * 处理消息
     *
     * @param packet
     * @param channelContext
     * @throws Exception
     */
    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        MyPacket helloPacket = (MyPacket) packet;
        String message = helloPacket.getText();
        int te = Integer.parseInt(message.substring(12, 14), 16);
        if (te==72){
            //判断不是心跳 (判断长度是否为12位) 长度吻合业务逻辑
            // 1查询数据库 tem表 查询到id  绑定tiobind  然后放入redis中
            BTypeCollector bTypeCollector = StringUtil.HexToDomain(message);
            Tio.bindUser(channelContext,bTypeCollector.getEid());
            System.err.println("TIO收到设备发送的数据为：   " + message);

            publishToMqtt(message); // 直接使用 mqttClient
        }
//        Tio.bindUser(channelContext,"163");

    }
    private void publishToMqtt(String message) {
        try {
            if (mqttClient != null) {
                mqttClient.publish("devicetopic", new MqttMessage(message.getBytes()));
                System.out.println("消息已经发布至MQTT: " + message);
            } else {
                System.err.println("MQTT客户端为空");
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    //    @Override
//    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
//        //收到消息 强转成自己的packet
//        MyPacket helloPacket = (MyPacket) packet;
//        //消息体
//        byte[] body = helloPacket.getBody();
//        String message = helloPacket.getText();
//        System.err.println("TIO收到设备发送的数据为：   "+message);
//        LocalDateTime dateTime = LocalDateTime.now();
//        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        System.err.println("数据发送的时间是"+dtf.format(dateTime));
//
//        // 将消息发布到MQTT
//        publishToMqtt(message,channelContext);
//
//
//    }


//    private void publishToMqtt(String message, ChannelContext ctx) {
//        try {
//            MqttClient mqttClient = (MqttClient) ctx.getAttribute("mqttClient");
//            mqttClient.publish("device/topic", new MqttMessage(message.getBytes()));
//            System.out.println("Message published to MQTT: " + message);
//        } catch (MqttException e) {
//            e.printStackTrace();
//        }
//    }

    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.err.println(dtf.format(dateTime));

    }
}






        //拿到消息体判断 消息体是否为null
        //如果为NUll则不走消息
        //如果有数据执行
        //1,解析字符串 拿到长度  长度吻合业务逻辑
        // 则处理消息 1查询数据库 tem表 查询到id  绑定tiobind  然后放入redis中
        //2,数据不够 则不进入判断
//        if (message!=null){
//            if (message.length()>150){
//                int te = Integer.parseInt(message.substring(12, 14), 16);
//                if (te==72){
//                    //判断不是心跳 (判断长度是否为12位) 长度吻合业务逻辑
//                    // 1查询数据库 tem表 查询到id  绑定tiobind  然后放入redis中
//                    BTypeCollector bTypeCollector = StringUtil.HexToDomain(message);
//                    Integer integer = temperatureControlMapper.selectByCode(bTypeCollector.getEid());
//                    if (integer!=null){
//                        Tio.bindUser(channelContext,bTypeCollector.getEid());
//                    }
//                    messagePublisher.publish(message);
//
//                }
//            }else if (message.length()==28){
//                messagePublisher.sendH(message);
//            }
//        }
//    }


